var pug = require("pug");
var fs = require("fs");
var formidable = require("formidable");

function start(res,req) {
  console.log("Request hand/ler 'start' was called.");
  var body = pug.renderFile("./views/start.pug",{
    "title":'Timothy',
    "h1":"start"
  });

  res.writeHead(200, {"Content-Type": "text/html"});
  res.write(body);
  res.end();
}

function upload(res,req){
  console.log("Request handler 'upload' was called.");
  
  var form = new formidable.IncomingForm();

  console.log("about to parse");
  form.parse(req,function(err,fields,files){
     console.log("parse done");
     fs.renameSync(files.upload.path,"/tmp/test.png");
     res.writeHead(200, {"Content-Type":"text/html"});
     res.write("received image:<br/>");
     res.write("<img src='/show' />");
     res.end();
  });
}

function show(res,req){
  console.log("Request handler 'show' was callec.");
  fs.readFile("/tmp/test.png","binary",function(err,file){
    if(err){
      res.writeHead(500,{"Content-Type":"text/plain"});
      res.write(err+"\n");
      res.end();
    }else{
      res.writeHead(200,{"Content-Type":"image/png"});
      res.write(file,"binary");
      res.end();
    }
  });
}
  
/*
module.exports = {
  start:start,
  upload:upload
}
*/
exports.start = start;
exports.upload = upload;
exports.show = show;